package com.huaxindata.im.main.manager;

import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.text.TextUtils;

import com.huaxindata.im.constants.ContactConstants;
import com.huaxindata.im.http.RetrofitClient;
import com.huaxindata.im.model.contact.Contact;
import com.huaxindata.im.model.contact.ContactGroup;
import com.huaxindata.im.model.contact.ContactLocal;
import com.huaxindata.im.model.contact.ContactPerson;
import com.huaxindata.im.model.db.ContactStore;
import com.huaxindata.im.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/8/16.
 * 本类需要一进入app就执行初始化的操作
 * 动态的管理联系人，主要包括以下几个功能，提供静态方法供访问
 * 1、从网络下载联系人到本地，并分类处理为好友，群组生成两个列表
 * 2、可以动态的从两个列表中删除某个好友或群组
 * 3、从数据库动态加载聊天历史记录联系人
 */

public class ContactManager {
    public static final String TAG = "ContactManager";

    private static List<Contact> sFriendList;//好友列表
    private static List<Contact> sGroupList;//群列表
    private static List<Contact> sColleagueList;//公司同事联系人列表
    private static List<Contact> sLocalList;//本地通讯录联系人列表
    private static List<String> sTopics=new ArrayList<>();
    /**
     * 获取用户信息（好友信息，同事信息，群信息）
     */
    public static void initData(){
        Call<String> call = RetrofitClient.getHttpApi().getUserList();
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                String body = response.body();
                parseContact(body);
                //此处刷新数据，在对应的数据集中要更新ui
                for (OnContactRefresh refresh : sRefreshList) {
                    refresh.onRefresh();
                }
            }
            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Log.e(TAG,"xxx==下载联系人出错："+t.getMessage());
                t.printStackTrace();
            }
        });
    }
    /**
     * 用于解析联系人
     */
    private static class ParserTask extends AsyncTask<String,Void,Boolean> {
        @Override
        protected Boolean doInBackground(String... params) {

            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                //此处刷新数据
                for (OnContactRefresh refresh : sRefreshList) {
                    refresh.onRefresh();
                }
            }
        }
    }

    /**
     * 解析联系人
     * @param result
     */
    private static void parseContact(String result){
        sFriendList=new ArrayList<>();
        sGroupList = new ArrayList<>();
        sColleagueList = new ArrayList<>();
        if (result == null) {
            Log.e(TAG,"xxx==下载的用户好友数据为空");
            return;
        }
        try {
            final JSONObject jsonObject = new JSONObject(result);
            if (jsonObject.has("userList")) {//解析好友列表
                final JSONArray jsonArray = jsonObject.getJSONArray("userList");
                parseFriendList(jsonArray);
            }
            if (jsonObject.has("colleagueList")) {//解析同事列表
                JSONArray colleagueArray = jsonObject.getJSONArray("colleagueList");
                parseColleagueList(colleagueArray);
            }
            //解析群列表
            if (jsonObject.has("groupList")) {
                final JSONArray jsonGroupArray = jsonObject.getJSONArray("groupList");
                parseGroupList(jsonGroupArray);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析群组
     * @param jsonGroupArray
     * @throws JSONException
     */
    private static void parseGroupList(JSONArray jsonGroupArray) throws JSONException {
        for (int i = 0; i < jsonGroupArray.length(); i++) {
            final JSONObject object = jsonGroupArray.getJSONObject(i);
            String groupClientId = object.has("groupClientId") ? object.getString("groupClientId") : "";
            String groupName = object.has("groupName") ? object.getString("groupName") : "";
            String groupMembers = object.has("groupMembers") ? object.getString("groupMembers") : "";
            String groupMain = object.has("groupMain") ? object.getString("groupMain") : "";
            String groupIcon = object.has("groupIcon") ? object.getString("groupIcon") : "";
            String groupMemberNickname = object.has("groupMembersNickName") ? object
                    .getString("groupMembersNickName") : "";
            String groupMemberImg = object.has("groupMembersImg") ? object.getString
                    ("groupMembersImg") : "";
            ContactGroup group = new ContactGroup(groupClientId,groupMain,groupName,groupIcon);
            group.setGroupMembers(groupMembers);
            group.setGroupMembersNickName(groupMemberNickname);
            group.setGroupMembersImg(groupMemberImg);
            sGroupList.add(group);
        }
    }

    /**
     * 解析好友
     * @param jsonArray
     * @throws JSONException
     */
    private static void parseFriendList(JSONArray jsonArray) throws JSONException {
        for (int i = 0; i < jsonArray.length(); i++) {
            final JSONObject object = jsonArray.getJSONObject(i);
            String id = object.has("id") ? object.getString("id") : null;
            if (id == null) {
                continue;
            }
            String nickName = object.has("nickName") ? object.getString("nickName") : null;
            String phone = object.has("phone") ? object.getString("phone") : null;
            String imgUrl = object.has("img") ? object.getString("img") : null;
            String title = object.has("title") ? object.getString("title") : "普通用户";
            String company = object.has("company") ? object.getString("company") : "暂无组织";
            ContactPerson person = new ContactPerson(id, nickName, imgUrl);
            person.setTitle(TextUtils.isEmpty(title) ? "普通用户" : title);
            person.setPhone(phone);
            person.setCompany(TextUtils.isEmpty(company) ? "暂无组织" : company);
            sFriendList.add(person);
            sTopics.add(id);
        }
    }
    /**
     * 解析同事列表
     */
    private static void parseColleagueList(JSONArray jsonArray) throws JSONException {
        for (int i = 0; i < jsonArray.length(); i++) {
            final JSONObject object = jsonArray.getJSONObject(i);
            String id = object.has("id") ? object.getString("id") : null;
            if (id == null) {
                continue;
            }
            String nickName = object.has("nickName") ? object.getString("nickName") : null;
            String phone = object.has("phone") ? object.getString("phone") : null;
            String imgUrl = object.has("img") ? object.getString("img") : null;
            String title = object.has("title") ? object.getString("title") : ContactConstants.CH_USER;
            String company = object.has("company") ? object.getString("company") : ContactConstants.CH_COMPANY;
            ContactPerson person = new ContactPerson(id, nickName, imgUrl);
            person.setTitle(TextUtils.isEmpty(title) ? "普通用户" : title);
            person.setPhone(phone);
            person.setCompany(TextUtils.isEmpty(company) ? "暂无组织" : company);
            sColleagueList.add(person);
        }
    }

    /**
     * 获取整个好友列表，如果为空，则从网络上下载
     * @return
     */
    public static List<Contact> getFriendList(){
        if (sFriendList == null) {
            initData();
            return null;
        }
        return sFriendList;
    }
    /**
     * 根据好友的id获取某个好友对象，找到了就返回，没有就返回为空
     * @param contactId
     * @return
     */
    public static Contact getContactById(String contactId){
        if (contactId == null) {
            return null;
        }
        if (sFriendList == null) {
            initData();
            return null;
        }
        for(Contact person:sFriendList){
            if (contactId.equals(person.getClientId())) {
                return person;
            }
        }
        return null;
    }
    /**
     * 从好友列表集合中删除某个好友
     */
    public static void removeFriend(String id){
        if (sFriendList == null) {
            initData();
        }
        for (Contact contact : sFriendList) {
            if (contact.getClientId().equals(id)) {
                sFriendList.remove(contact);
                break;
            }
        }
        //此处刷新数据，在对应的数据集中要更新ui
        for (OnContactRefresh refresh : sRefreshList) {
            refresh.onRefresh();
        }
    }

    /**
     * 根据好友的id获取某个对象，找到了就返回，没有就返回为空
     * @param contactId
     * @return
     */
    public static Contact getColleagueById(String contactId){
        if (contactId == null) {
            return null;
        }
        if (sColleagueList == null) {
            initData();
            return null;
        }
        for(Contact person:sColleagueList){
            if (contactId.equals(person.getClientId())) {
                return person;
            }
        }
        return null;
    }

    /**
     * 获取所有的群列表，如果群列表为空，则从网络上下载
     * @return ：
     */
    public static List<Contact> getGroupList(){
        if (sGroupList == null) {
            initData();
            return null;
        }
        return sGroupList;
    }

    /**
     * 通过群id获取某个群组，找到了就返回，没有就返回为空
     * @param groupId
     * @return
     */
    public static Contact getGroupById(String groupId){
        if (groupId == null) {
            return null;
        }
        if (sGroupList == null) {
            initData();
            return null;
        }
        for (Contact group:sGroupList) {
            if (groupId.equals(group.getClientId())) {
                return group;
            }
        }
        return null;
    }

    /**
     * 删除某个群组
     */
    public static void removeGroup(String groupId){
        if (sGroupList == null) {
            initData();
        }
        if (TextUtils.isEmpty(groupId)) {
            return;
        }
        int size=sGroupList.size();
        for (int i = 0; i < size; i++) {
            Contact group = sGroupList.get(i);
            if (group.getClientId().equals(groupId)) {
                sGroupList.remove(i);
                break;
            }
        }
        //此处刷新数据
        for (OnContactRefresh refresh : sRefreshList) {
            refresh.onRefresh();
        }
    }
    /**
     * 根据指定id判断是不是好友
     * @param id
     */
    public static boolean isFriend(String id){
        if (id == null) {
            return false;
        }
        if (sFriendList == null) {
            initData();
        }
        for (Contact person:sFriendList) {
            if (id.equals(person.getClientId())) {
                return true;
            }
        }
        return false;
    }
    /**
     * 根据指定id判断是不是群
     * @param id
     */
    public static boolean isGroup(String id){
        if (id == null) {
            return false;
        }
        if (sGroupList == null) {
            initData();
        }
        for (Contact person:sGroupList) {
            if (id.equals(person.getClientId())) {
                return true;
            }
        }
        return false;
    }
    public static List<Contact> getColleagueList(){
        if (sColleagueList == null) {
            initData();
            return null;
        }
        return sColleagueList;
    }
    /**
     * 读取手机通讯录
     * @return
     */
    public static List<Contact> loadLocalContactList(Context context){
        if (sLocalList != null) {
            //如果已经初始化，说明加载过本地联系人，不用重新加载
            return sLocalList;
        }
        sLocalList = new ArrayList<>();
        try {
            Cursor cursor =context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
                    new String[]{ContactsContract.Contacts._ID,
                            ContactsContract.Contacts.DISPLAY_NAME,
                            ContactsContract.Contacts.HAS_PHONE_NUMBER,
                            "sort_key"}, null, null,
                    "sort_key COLLATE LOCALIZED asc");

            while (cursor != null && cursor.moveToNext()) {
                final String has_phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                if ("1".equals(has_phoneNumber)) {
                    ContactLocal contact = new ContactLocal();
                    contact.clientId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                    contact.nickName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                    sLocalList.add(contact);
                }
            }
            if (cursor != null)
                cursor.close();
            queryPhone(context);
            return sLocalList;
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 获取电话号码
     */
    private static void queryPhone(Context context) {
        Cursor phones = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
                new String[]{ContactsContract.Data.CONTACT_ID,
                        ContactsContract.CommonDataKinds.Phone.NUMBER},
                ContactsContract.Data.MIMETYPE
                        + "='"
                        + ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
                        + "'", null, null);
        while (phones.moveToNext()) {
            final String contactId = phones.getString(phones.getColumnIndex(ContactsContract.Data.CONTACT_ID));
            for (Contact contact : sLocalList) {
                if (contactId.equals(contact.clientId)) {
                    contact.phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    break;
                }
            }
        }
        phones.close();
    }
    /**
     * 获取要订阅的所有主题
     * @return
     */
    public static String[] getTopics(){
        //sTopics里包含群id组成的主题
        sTopics.add("chat/general");//订阅默认主题
        sTopics.add("chat/"+ UserManager.getClientId());//订阅自己的主题
        return sTopics.toArray(new String[]{});
    }
    /**
     * 获取最近联系的好友和群
     * @return
     */
    public static List<ContactPerson> getRecentContact(){
        return ContactStore.queryRecentContact();
    }
    private static List<OnContactRefresh> sRefreshList = new ArrayList<>();
    public static void addContactRefreshListenner(OnContactRefresh OnContactRefresh){
        sRefreshList.add(OnContactRefresh);
    }
    public static void removeContactRefreshListenner(OnContactRefresh OnContactRefresh){
        sRefreshList.remove(OnContactRefresh);
    }
    public interface OnContactRefresh {
        void onRefresh();

    }
}
